--
-- Author: ping.wang
-- Date: 2018-07-11 14:03:01
--
-- AuctionNormalSellRender
--

local ClassRef = app.mvc.createRenderClass(...)
local string_format = string.format
local string_split = string.split
local table_insert = table.insert
local math_floor = math.floor
local auctionSellPriceRateLimite = GD:getSystemPar( "auctionSellPriceRateLimite",20)
local auctionAdjustPriceRate = GD:getSystemPar( "auctionAdjustPriceRate",1)
local auctionRate = GD:getSystemStrPar("auctionDutyRate")

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.AuctionSell1Render))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._soldTotalPriceText = self._ui.Panel_num_total:findChild("num") --出售总价
    self._taxText = self._ui.Panel_num_poundage:findChild("tlt")
    self._taxText:setString(L("auction_tax"))
    self._poundageNumText = self._ui.Panel_num_poundage:findChild("num") --手续费

    self._seperatePriceText = self._ui.Panel_supplies_1:findChild("num/num") --推荐单价
    self._seperatePrice = 0 --单价 可以被修改

    local priceMinusBtn = self._ui.Panel_supplies_1:findChild("Button_minus") --减少价格的按钮
    local pricePlusBtn = self._ui.Panel_supplies_1:findChild("Button_plus") --增加价格的按钮
    priceMinusBtn:addTouchEventListener(handler( self, self._minusPriceBtnClickEvent ) )
    pricePlusBtn:addTouchEventListener(handler( self, self._plusPriceBtnClickEvent ) )

    self._soldCountText =self._ui.Panel_supplies:findChild("num") --出售数量 可以被修改
    self._soldCount = 0

    local soldCountMinusBtn = self._ui.Panel_supplies:findChild("Button_minus") --减少数量的按钮
    local soldCountPlusBtn = self._ui.Panel_supplies:findChild("Button_plus") --增加数量的按钮
    soldCountMinusBtn:addTouchEventListener(handler( self, self._minusSoldCountBtnClickEvent ) )
    soldCountPlusBtn:addTouchEventListener(handler( self, self._plusSoldCountBtnClickEvent ) )

    self._ui.btn_sell:addClickEventListener(handler( self, self._startSellItem ) )

    ----------小键盘start--------------
    local suppliesPanelBg = self._ui.Panel_supplies:findChild("bg")

    display.uiAddClick( suppliesPanelBg, function()
        local btn = self._ui.Panel_supplies:findChild("Button_plus")
        local posTemp = btn:convertToWorldSpace(cc.p(0,0))
        local width, height = btn:getContentSize2()
        posTemp.x = posTemp.x + width

        executeFunc(self._onClick, "showMiniKeyboard", {posTemp,self._soldCount,handler( self, self.setAndGetSoldCount )} )
    end )
    ----------小键盘end----------------

    self:setContentSize( self._ui.Panel:getContentSize() )
    self._showTipsFlag = false
    local rateString = string_split(auctionRate,"|")
    self._rateValue = {}
    for _,v in ipairs(rateString) do
        local temp = string_split(v,":")
        table_insert(self._rateValue,{tonumber(temp[1]),tonumber(temp[2])})
    end

    --普通商品的出售 icon
    local goldIcon1 = self._ui.Panel_num_total:findChild("gold")
    local goldIcon2 = self._ui.Panel_supplies_1:findChild("num/gold")
    local goldIcon3 = self._ui.Panel_num_poundage:findChild("gold")

    local iconId = tonumber(GD:getSystemPar( "auctionNormalGoodsLootType",99))
    local coinConfig = GD:getCoinConfig(iconId)
    local iconPath = string.format("%s%s.png",Res.coinIconPath,coinConfig.bigicon)
    goldIcon1:loadTexture(iconPath)
    goldIcon2:loadTexture(iconPath)
    goldIcon3:loadTexture(iconPath)


    self:refresh()
end

---data = {itemData = itemData, suggestPrice = price, isbuy = false}
function ClassRef:refresh()
    if self._data then
        self:setVisible( true )

        self._itemData = self._data.itemData

        if self._itemData.itemBagType == Enums.ItemBagType.equip then
            self._suggestPrice = self._itemData:getSuggestPrice()
        else
            if not self._data.suggestPrice then
                self._suggestPrice = self._itemData:getSuggestPrice()
            else
                self._suggestPrice = self._data.suggestPrice
            end
        end
    
        self._originalSeperatePrice = self._suggestPrice --记录一个初始值

        self:_setSeperatePrice(self._suggestPrice) --默认设置单价为推荐单价
        self:setAndGetSoldCount(self._itemData:getAmount()) --默认设置数量为道具的数量

    else
        self:setVisible( false )
    end
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end

--调整有文字的价格以及描述金币的位置
function ClassRef:_adjustIconPosAndDes(text,priceText,icon)
    local textWidth = text:getContentSize().width
    local priceWidth = priceText:getContentSize().width
    local parentWidth = text:getParent():getContentSize().width
    local startPosX = (parentWidth - priceWidth)/2
    text:setPositionX(startPosX - 10)
    priceText:setPositionX(parentWidth/2 + textWidth/2)
    icon:setPositionX((parentWidth+ textWidth + priceWidth)/2 + icon:getContentSize().width * 0.6)
end

--计算手续费和总价
function ClassRef:_calculateTotalAndPoundage()
    local rateVal = 0
    for _,v in ipairs(self._rateValue) do
        if self._seperatePrice > v[1] and rateVal < v[2] then
            rateVal = v[2]
        end
    end

    local poundagePercent = rateVal/100 --万分比税率 最少为0

    self._totalPrice = self._seperatePrice * self._soldCount
    local poundageNum = math_floor(self._totalPrice * poundagePercent)

    self._poundageNumText:setString(tostring(poundageNum))
    self._soldTotalPriceText:setString(tostring(self._totalPrice))

    self:_adjustIconPosAndDes(self._ui["Panel/Panel_num_total/tlt"],self._soldTotalPriceText,self._ui["Panel/Panel_num_total/gold"])

    self:_adjustIconPosAndDes(self._ui["Panel/Panel_num_poundage/tlt"],self._poundageNumText,self._ui["Panel/Panel_num_poundage/gold"])
end

function ClassRef:_setSeperatePrice(num)
    num = math_floor(num)
    --单价为推荐价格的%20左右的浮动 且 >= 1
    local minPrice = self._itemData:getMinSoldPrice()
    --local minPrice = math_floor(self._originalSeperatePrice * (100 - auctionSellPriceRateLimite) / 100)
    local maxPrice = math_floor(self._originalSeperatePrice * (100 + auctionSellPriceRateLimite) / 100)

    local suggestMinPrice = self._itemData:getMinSoldPrice()
    local suggestMaxPrice = self._itemData:getMaxSoldPrice()

    if num < minPrice then
        self._seperatePrice = minPrice
        if self._showTipsFlag then
            display.pushToast(L("auction_tips13"))
            self._showTipsFlag = false
        end
    elseif num > maxPrice then
        self._seperatePrice = maxPrice
        self:_showTipsByPrecent(string_format(L("auction_tips6"),auctionSellPriceRateLimite))
    else
        self._seperatePrice = num
    end

    if self._seperatePrice < suggestMinPrice then
        self._seperatePrice = suggestMinPrice
        self:_showTipsByPrecent(L("action_minprice_notice"))
    elseif self._seperatePrice > suggestMaxPrice then
        self._seperatePrice = suggestMaxPrice
        self:_showTipsByPrecent(L("action_maxprice_notice"))
    end

    self._seperatePriceText:setString(string_format(L("auction_singlePrice"),self._seperatePrice))
    self:_calculateTotalAndPoundage()
end

--达到上限的时候显示一次tips
function ClassRef:_showTipsByPrecent(str)
    if self._showTipsFlag then
        display.pushToast(str)
        self._showTipsFlag = false
    end
end

function ClassRef:setAndGetSoldCount(num)
    --数量不可以小于1 且不能大于自己拥有的数量
    local itemData = self._itemData
    local totalCount = itemData:getAmount()
    if num < 1 then
        self._soldCount = 1
    elseif num > totalCount then
        self._soldCount = totalCount
    else
        self._soldCount = num
    end

    local minNum = itemData:getAcMinNum()
    local maxNum = itemData:getAcMaxNum()

    if self._soldCount < minNum then
        self._soldCount = minNum
    elseif self._soldCount > maxNum then
        self._soldCount = maxNum
    end

    self._soldCountText:setString(string_format(L("auction_tradeNum"),self._soldCount,totalCount))
    self:_calculateTotalAndPoundage()
    return self._soldCount
end

--减少数量
function ClassRef:_minusSoldCountBtnClickEvent(sender,eventType)
    self:_doLongPressClickEvent(sender,eventType,function() self:setAndGetSoldCount(self._soldCount - 1) end)
end

--增大数量
function ClassRef:_plusSoldCountBtnClickEvent(sender,eventType)
    self:_doLongPressClickEvent(sender,eventType,function() self:setAndGetSoldCount(self._soldCount + 1) end)
end

--减少单价
function ClassRef:_minusPriceBtnClickEvent(sender,eventType)
    self:_doLongPressClickEvent(sender,eventType,function() self:_minusSepeartePrice() end)
end

--增大单价
function ClassRef:_plusPriceBtnClickEvent(sender,eventType)
    self:_doLongPressClickEvent(sender,eventType,function() self:_plusSepeartePrice() end)
end

--按比率增加和减少单价 无法手动修改具体的价格
function ClassRef:_minusSepeartePrice()
    local val = math_floor(auctionAdjustPriceRate * self._originalSeperatePrice/100)
    if val == 0 then
        val = 1
    end
    self:_setSeperatePrice(self._seperatePrice - val)
end

function ClassRef:_plusSepeartePrice()
    local val = math_floor(auctionAdjustPriceRate * self._originalSeperatePrice/100)
    if val == 0 then
        val = 1
    end
    self:_setSeperatePrice(self._seperatePrice + val)
end

function ClassRef:_doLongPressClickEvent(sender,eventType,callFunc)
    if eventType == ccui.TouchEventType.began then
        self._showTipsFlag = true
        self._delayPressAction = self:performWithDelay(
            function()
                if not self._longPressAction then
                    self._longPressAction = self:schedule(callFunc,0.05)
                end
            end,0.3) --0.3秒后执行回调

    elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then

        if self._delayPressAction then
            self:stopAction(self._delayPressAction)
            self._delayPressAction = nil
        end

        if self._longPressAction then
            self:stopAction(self._longPressAction)
            self._longPressAction = nil
        else
            callFunc()
        end
        self._showTipsFlag = false
    end
end

function ClassRef:_startSellItem()
    --需要UUID sellPrice count
    executeFunc(self._onClick, "normalSell",{self._itemData:getUid(),self._seperatePrice,self._soldCount})
end

return ClassRef
